<template>
  <BasicModal v-bind="$attrs" @register="register" :title="getTitle" width="70%">
    <a-spin :spinning="loading" size="large" tip="Loading...">
      <a-form ref="formRef" class="antd-modal-form">
        <p style="text-align: center">
          <span style="width: 35%; text-align: center; font: 1.7em sans-serif">{{ formData.samName }}</span
          ><br />
          <span style="width: 35%; text-align: center; font: 1.7em sans-serif">检验结果报告单</span>
        </p>
        <table id="items" cellspacing="1" style="width: 100%; height: 150px; border: 1px solid #a8aeb2">
          <tr class="tr">
            <th class="thC">依据标准:</th>
            <th class="thE" :colspan="3"><a-input v-model:value="formData.basisName" size="large" class="input" readonly="true" /></th>
          </tr>
          <tr class="tr">
            <th class="thC">样品编号:</th>
            <td class="thE"><a-input v-model:value="formData.samNum" size="large" class="input" readonly="true" /></td>
            <td class="thC">报告编号:</td>
            <td class="thE"><a-input v-model:value="formData.reportNum" size="large" class="input" /></td>
          </tr>
          <tr class="tr">
            <th class="thC">填报日期:</th>
            <td class="thE"><a-date-picker valueFormat="YYYY-MM-DD" v-model:value="formData.reportDate" size="large" class="input" /></td>
            <td class="thC"></td>
            <td class="thE"></td>
          </tr>
        </table>
        <!--项目列表-->
        <labItemsTable ref="registerItemsTable" @deleteItem="deleteItem" :labEntrustItemsList="labEntrustItemsIndexPageList"></labItemsTable>
        <table id="items" cellspacing="1" style="width: 100%; height: 250px; border: 1px solid #a8aeb2">
          <tr class="tr">
            <th class="thB">检验结论</th>
            <th style="width: 20%; text-align: center; border: 1px solid #a8aeb2; font: 1.1em sans-serif" colspan="5"
              ><a-textarea v-model:value="formData.reportConcl" size="large" class="input"
            /></th>
          </tr>
          <tr class="tr">
            <th class="thB">备注</th>
            <th style="width: 20%; text-align: center; border: 1px solid #a8aeb2; font: 1.1em sans-serif" colspan="5"
              ><a-textarea v-model:value="formData.remark" size="large" class="input"
            /></th>
          </tr>
          <tr style="height: 40px; border: 1px solid #a8aeb2">
            <th class="thB">批准人</th>
            <th style="width: 20%; text-align: center; border: 1px solid #a8aeb2; font: 1.1em sans-serif"
              ><a-input v-model:value="formData.ratifyName" size="large" class="input" @click="handleRatifyModal"
            /></th>
            <th class="thB">审核人</th>
            <th style="width: 20%; text-align: center; border: 1px solid #a8aeb2; font: 1.1em sans-serif"
              ><a-input v-model:value="formData.auditName" size="large" class="input" @click="handleAuditModal"
            /></th>
            <th class="thB">主检人</th>
            <th style="width: 20%; text-align: center; border: 1px solid #a8aeb2; font: 1.1em sans-serif"
              ><a-input v-model:value="formData.checkName" size="large" class="input" readonly="true"
            /></th>
          </tr>
        </table>
      </a-form>
    </a-spin>
    <template v-slot:footer>
      <a-button type="default" @click="closeModal">取消</a-button>
      <a-button type="primary" :disabled="!disabledPreview" :loading="loading" @click="handleSubmit">生成报告</a-button>
      <a-button type="primary" :disabled="disabledPreview" @click="previewReport">报告预览</a-button>
      <!-- <a-button type="primary" @click="previewReport">报告预览</a-button> -->
      <a-button type="primary" :disabled="disabledPreview" @click="submitReport">提交报告</a-button>
    </template>
    <div style="display: none">
      <iframe id="pdfPreviewIframe" :src="url" frameborder="0" width="100%" height="550px" scrolling="auto"></iframe>
    </div>
  </BasicModal>
  <TableUserModal @register="registerUserModal" @getRatifyResult="onRatifyOk" @getAuditResult="onAuditOk"></TableUserModal>
  <PdfViewer v-if="openPdf" :pdfUrl="jsPdf" @closePdf="closePdf"></PdfViewer>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { ref, reactive } from 'vue';
  import labItemsTable from './LabCheckItemsTableB.vue';
  import TableUserModal from './LabUserTableList.vue';
  import { queryReportData, saveOrUpdateData, sumbitReport } from './LabItemReportList.api';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { useUserStore } from '/@/store/modules/user';
  import { defHttp } from '/@/utils/http/axios';
  import PdfViewer from './subTables/pdfViewer.vue';
  import { useGlobSetting } from '/@/hooks/setting';
  import { getToken } from '/@/utils/auth';

  const globSetting = useGlobSetting();
  const baseApiUrl = globSetting.domainUrl;
  let disabledPreview = ref(true);
  let openPdf = ref(false);
  let jsPdf = ref("");
  const url = ref(`${baseApiUrl}/sys/common/pdf/pdfPreviewIframe`);

  const registerItemsTable = ref();
  const formRef = ref();
  const emit = defineEmits(['success', 'reporting']);
  const loading = ref(true);
  const getTitle = ref('检验结果报告单');
  const receiveParams = ref([]);
  const { userInfo } = useUserStore();
  let previewParams = {};
  const formData = reactive<Record<string, any>>({
    id: '',
    samName: '',
    samNum: '',
    basisName: '',
    basisNum: '',
    reportNum: '',
    reportDate: null,
    reportConcl: '',
    remark: '',
    taskId: '',
    checkId: '',
    checkName: '',
    auditId: '',
    auditName: '',
    ratifyId: '',
    ratifyName: '',
    labEntrustItemsList: [],
    entrustId: '',
    entrustType: '',
  });
  let labEntrustItemsIndexPageList = ref({});

  const [registerUserModal, { openModal: openUModal }] = useModal();

  function handleRatifyModal() {
    openUModal(true, {
      oper: 'ratify',
    });
  }

  function handleAuditModal() {
    openUModal(true, {
      oper: 'audit',
    });
  }

  //批准
  function onRatifyOk(uId, uName) {
    formData.ratifyId = uId;
    formData.ratifyName = uName;
  }
  //审核
  function onAuditOk(uId, uName) {
    formData.auditId = uId;
    formData.auditName = uName;
  }

  const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({
      // minHeight: 800,
    });
    formData.taskId = data.record.id;
    receiveParams.value = data.record;
    disabledPreview.value = true;
    previewParams = {
      entrustType: data.record.entrustType,
      reportCode: formData.reportNum,
      userName: userInfo.realname,
    };
    let params = {
      taskId: formData.taskId,
      entrustType: data.record.entrustType,
    };
    await queryReportData(params)
      .then((res) => {
        Object.assign(formData, res);
        console.log('formData', formData);
        formData.entrustType = data.record.entrustType;
        labEntrustItemsIndexPageList.value = JSON.parse(JSON.stringify(formData.labEntrustItemsIndexPageList));
        console.log('labEntrustItemsIndexPageList', labEntrustItemsIndexPageList);
      })
      .finally(() => {
        loading.value = false;
      });
  });

  //删除实验重复数据
  const deleteItem = (record) => {
    formData.labEntrustItemsIndexPageList.forEach((element, index) => {
      // if(element.id===record.id){
      if (element.taskItemsId === record.taskItemsId) {
        formData.labEntrustItemsIndexPageList[index].reportMark = '0';
      }
    });
    labEntrustItemsIndexPageList.value = labEntrustItemsIndexPageList.value.filter((item) => item.taskItemsId !== record.taskItemsId);
  };

  //提交表单数据
  async function handleSubmit() {
    formData.auditId = formData.auditId;
    formData.auditName = formData.auditName;
    mergeData()
    // console.log(formData);
    if (formData.auditName != '' && formData.auditName != null && formData.ratifyName != '' && formData.ratifyName != null) {
      loading.value = true;
      await saveOrUpdateData(formData)
        .then((res) => {
          Object.assign(formData, res.result);
          // console.log('res',res);
          jsPdf.value = `${baseApiUrl}/sys/common/static${res.result.pfdFile}`;
          // console.log('jsPdf',jsPdf.value);
          setTimeout(()=>{
            createMessage.success('生成报告成功！');
            disabledPreview.value = false;
            loading.value = false;
          },10000);
          // loading.value = false;
        })
        .finally(() => {
          // closeModal();
          // emit('success');
          // loading.value = false;
          // disabledPreview.value = false;
        });
    } else {
      createMessage.warning('请选择批准和审核人员!');
    }
  }
  //报告预览
  function previewReport() {
    const urlArr = formData.pfdFile.split('/');
    const title = urlArr[urlArr.length-1]; 
    let encodedUrl = `${baseApiUrl}/sys/common/static${formData.pfdFile}`;
    // let encodedUrl = `${baseApiUrl}/sys/common/static/labpdf/压裂酸化用减阻剂 改性聚丙烯酰胺 CT1-20D-委托检验-(2024) W (699).pdf`;
    let iframe = document.getElementById('pdfPreviewIframe');
    let json = { title: title, token: getToken(), url: encodedUrl};
    iframe.contentWindow.postMessage(json, '*');
  }
  
  function closePdf() {
    openPdf.value = false;
  }

  // 提交报告
  async function submitReport() {
    mergeData()
    loading.value = true;
    //暂时屏蔽签名
    // updateSign();
    try {
      let result = await sumbitReport(formData);
      loading.value = false;
      if (result.code === 200) {
        createMessage.success(result.message);
        closeModal();
        emit('success');
      }
    } catch {
      loading.value = false;
    }
  }

  function mergeData(){
    let mergedArray = [];
    // 将 formData.labEntrustItemsIndexPageList 复制到 mergedArray
    mergedArray = formData.labEntrustItemsIndexPageList.slice();

    // 遍历 labEntrustItemsIndexPageList.value
    labEntrustItemsIndexPageList.value.forEach((element) => {
      // 检查是否有相同 id 的元素在 formData.labEntrustItemsIndexPageList 中
      let existingElementIndex = mergedArray.findIndex((item) => item.id === element.id);
      if (existingElementIndex !== -1) {
        // 如果存在相同 id 的元素，则进行合并
        Object.assign(mergedArray[existingElementIndex], element);
      } else {
        // 如果不存在相同 id 的元素，则将该元素添加到 mergedArray 中
        mergedArray.push(element);
      }
    });

    // 更新 formData.labEntrustItemsIndexPageList
    formData.labEntrustItemsIndexPageList = mergedArray;
  }


  // 更新签名
  async function updateSign() {
    let signature = '/entrust/labEntrust/signature';
    let servestoken = '/entrust/labEntrust/serveToken';
    //获取服务token和员工票据,员工id
    await defHttp.get({ url: servestoken }, { isTransformResponse: false }).then((srcs) => {
      //员工id
      let yaunid = srcs.cardid;
      //let yaunid = 43;
      //服务token
      let tokenServe = srcs.tokenServe;
      //let tokenServe = "eyJ0eXAiOiJqd3QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1MDcyNzUxNDc0NDM0Mzc1NjgiLCJhdWQiOiJiYXNlIiwiaXNzIjoiemh1bnplIiwiZXhwIjoxNzAxMzQwNzgzLCJpYXQiOjE3MDEzMzI5ODN9.f4zHoRe2Z0lvE5HTmRQUqOmlYP9ygQhC_X8icNHhsuY";
      //员工票据
      let employeeTicket = srcs.employeeTicket;
      //let employeeTicket = "22a64aa46829dacaca9f4e10221de1b215be653d";
      //封装请求
      let datae = {
        businessCreateUserId: yaunid,
        businessCreateUserPositionId: '',
        content: 'flowlame=12',
        description: '',
        name: '12',
      };
      //调用签证
      //获取签名
      window.SCZZ_SIGN.open({
        token: employeeTicket, //员工票据，通过获取员工票据接口获取得到
        data: datae, //签证数据,用于签证校验，其内容见下文
        type: 'PERSONAL_SIGNATURE', //类型（个人签名:PERSONAL_SIGNATURE，单位签章:CORP_SIGNATURE），根据不同的类型打开对应的签证页面
        mobile: false, //移动端调用时需要传递
        call: async function (res) {
          loading.value = false;
          if (res.data.imageUrl) {
            console.log(res.data.imageUrl);
            console.log('yaunid', yaunid);
            loading.value = true;
            try {
              console.log('提交的表单数据', formData);
              let result = await sumbitReport(formData);
              loading.value = false;
              if (result.code === 200) {
                createMessage.success(result.message);
                closeModal();
                emit('success');
              }
            } catch {
              loading.value = false;
            }
            // 把签名存在数据库
            let urls = signature + '?id=' + yaunid + '&paramasa=' + res.data.imageUrl;
            defHttp.post({ url: urls }, { isTransformResponse: false });
          } else {
            // createMessage.error('签名失败，请重新签名！');
          }
          //回调，接收一个结果对象，该对象里包含sdk的响应状态码code，响应信息msg，当响应code为1000时有响应数据data，响应数据内容见下文
        },
      });
    });
  }
</script>

<style scoped>
  .header {
    line-height: 35px;
    background-color: #f2f2f2;
    color: #666;
  }

  .tr {
    height: 50px;
    border: 1px solid #a8aeb2;
  }
  .thA {
    width: 75%;
    text-align: center;
    border: 1px solid #a8aeb2;
    font: 1.1em sans-serif;
  }
  .thB {
    width: 15%;
    text-align: center;
    border: 1px solid #a8aeb2;
    font: 1.1em sans-serif;
  }

  .thC {
    width: 20%;
    text-align: center;
    border: 1px solid #a8aeb2;
    font: 1.1em sans-serif;
  }

  .thD {
    width: 80%;
    text-align: center;
    border: 1px solid #a8aeb2;
    font: 1.1em sans-serif;
  }

  .thE {
    width: 30%;
    text-align: center;
    border: 1px solid #a8aeb2;
    font: 1.1em sans-serif;
  }

  .input {
    width: 100%;
    height: 100%;
    border: none;
    background-color: inherit;
    outline: none;
    border-bottom: none;
    font: 1em sans-serif;
  }
</style>
<style scoped lang="less">
  :deep(.ant-modal-root .ant-modal-footer) {
    padding: 20px 16px;
  }
</style>
